package com.example.dotavideo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.apache.http.client.ClientProtocolException;

import android.R.integer;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.dotavideo.R;
import com.example.dotavideo.adapter.ChildListAdapter;
import com.example.dotavideo.adapter.VideoAdapter;
import com.example.dotavideo.base.DotaVideoApplication;
import com.example.dotavideo.bean.TypeBean;
import com.example.dotavideo.bean.VideoBean;
import com.example.dotavideo.util.CommonsUtil;
import com.example.dotavideo.util.HttpUtil;
import com.example.dotavideo.util.JsonUtil;

public class MainActivity extends BaseActivity {

  private TextView tvTitle;

  private final static int GET_CHILD_VIDEO = 0;
  private final static int GET_MORE = 1;
  private final static int GET_TYPE_OK = 10;
  private final static int GET_TYPE_ERROR = 11;

  private final static int GET_LIST_OK = 20;
  private final static int GET_LIST_ERROR = 21;
  private DotaVideoApplication application;

  private ArrayList<TypeBean> typeList = new ArrayList<TypeBean>();
  private ArrayList<VideoBean> videoList = new ArrayList<VideoBean>();
  private Context context;
  private PopupWindow popChildren;
  private ListView listView;
  private ImageView ivLeftMenu;
  private ImageButton btnSelectChild;
  private String currentId = "-1";
  private int currentPage = 0;
  private int currentTotalPage = 0;
  private TextView tvChildTitle;
  private TypeBean bean;
  private VideoAdapter adapter;
  private View footer;


  Handler handler = new Handler() {

    public void handleMessage(android.os.Message msg) {

      switch (msg.what) {
        case GET_TYPE_OK:
          baseTypelist = typeList;
          notifyChange();
          break;
        case GET_LIST_OK:
          if (adapter == null) {
            adapter = new VideoAdapter(context, videoList, handler);
            listView.addFooterView(footer);
            listView.setAdapter(adapter);
          } else {
            Log.e("Main ====", "notify");
            adapter.notifyDataSetChanged();
            if (currentPage == 0) {
              listView.setSelection(0);
            }
          }
          break;
        case GET_TYPE_ERROR:

          break;
        case GET_LIST_ERROR:

          break;
        case GET_MORE:
          if (currentPage == currentTotalPage - 1) {
            listView.removeFooterView(footer);
            Toast.makeText(context, "没有更多视频", Toast.LENGTH_SHORT).show();
          } else {
            currentPage++;
            getVideoByType(currentId, currentPage);
          }
          break;
        case GET_CHILD_VIDEO: {
          Bundle data = msg.getData();
          String key = data.getString("key");
          Map<String, String> childMap = bean.getChildType();
          tvChildTitle.setText("来源：" + key);
          String id = childMap.get(key);
          currentId = id;
          currentPage = 0;
          getVideoByType(id, currentPage);
          popChildren.dismiss();
        }
          break;
        default:
          break;
      }
    };
  };



  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub

    if (keyCode == KeyEvent.KEYCODE_BACK) {
      if (popChildren != null) {
        if (popChildren.isShowing()) {
          popChildren.dismiss();
          return true;
        }
      }
    }
    return super.onKeyDown(keyCode, event);
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    application = DotaVideoApplication.getInstance();

    this.context = this;

    getVideoByType(currentId, currentPage);

    initTypeData(application.URL_TYPE_DOTA1);

    findViews();
    setListeners();

  }

  private void setListeners() {
	 
	ivLeftMenu.setOnClickListener(new OnClickListener() {
		@Override
		public void onClick(View v) {
			getSlidingMenu().showMenu();
		}
	});
	  
	  
    btnSelectChild.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View view) {
        if (popChildren != null) {
          popChildren.setAnimationStyle(R.style.AnimationFade);
          if (popChildren.isShowing()) {
            popChildren.dismiss();
          } else {
            popChildren.showAsDropDown(view);
          }

        }
      }
    });

    listView.setOnTouchListener(new OnTouchListener() {
      @Override
      public boolean onTouch(View arg0, MotionEvent arg1) {
        if (popChildren != null) {
          if (popChildren.isShowing()) {
            popChildren.dismiss();
          }
        }
        return false;
      }
    });

    listView.setOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        Intent intent = new Intent(context,VideoActivity.class);
        Bundle data = new Bundle();
        data.putSerializable("video", videoList.get(position));
        if(position - 1 > 0){
        	data.putSerializable("video1", videoList.get(position-1));
        } else if(position + 1 < videoList.size() - 1){
        	data.putSerializable("video2", videoList.get(position + 1));
        } else if(position + 2 < videoList.size() - 1){
        	data.putSerializable("video3", videoList.get(position + 2));
        }
        
        intent.putExtra("list",data);
        
        context.startActivity(intent);
      }
    });



  }

  private void findViews() {
    footer = CommonsUtil.createListViewLoadMore(context);
    listView = (ListView) findViewById(R.id.lv_vedio);
    tvTitle = (TextView) findViewById(R.id.tv_title);
    ivLeftMenu = (ImageView) findViewById(R.id.iv_left_menu);
    
    btnSelectChild = (ImageButton) findViewById(R.id.btn_select_children);
    tvChildTitle = (TextView) findViewById(R.id.tv_child);

  }

  // 得到type数据
  private void initTypeData(final String url) {
    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          String json = HttpUtil.doPost(url, "");
          typeList.clear();
          typeList.addAll(JsonUtil.wrapTypeBeanList(json));
          handler.sendEmptyMessage(GET_TYPE_OK);

        } catch (ClientProtocolException e) {
          handler.sendEmptyMessage(GET_TYPE_ERROR);
          e.printStackTrace();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          handler.sendEmptyMessage(GET_TYPE_ERROR);
          e.printStackTrace();
        }
      }
    }).start();

  }

  // 得到子类下的视频
  private void getVideoByType(final String typeId, final int page) {
    new Thread(new Runnable() {
      @Override
      public void run() {
        try {

          String json =
              HttpUtil.requestByGet(application.URL_LIST_FROM_TYPE + "?page=" + page + "&catId="
                  + typeId);
          if (page == 0) {
            if (videoList != null && videoList.size() > 0) {
              videoList.clear();
            }
            // Log.e("Main--->", json);
          }

          ArrayList<VideoBean> list = JsonUtil.wrapVideoBeanList(json);
          currentTotalPage = list.get(0).getTotalPage();
          videoList.addAll(list);

          handler.sendEmptyMessage(GET_LIST_OK);

        } catch (ClientProtocolException e) {
          handler.sendEmptyMessage(GET_LIST_ERROR);
          e.printStackTrace();
        } catch (IOException e) {
          handler.sendEmptyMessage(GET_LIST_ERROR);
          e.printStackTrace();
        }
      }
    }).start();

  }

  @Override
  public void dataChange(String id) {

    if (!id.equals(currentId)) {

      currentId = id;
      currentPage = 0;
      getVideoByType(currentId, currentPage);

      if (id.equals("-1")) {
        tvTitle.setText("最近更新");
        tvChildTitle.setVisibility(View.INVISIBLE);
        btnSelectChild.setVisibility(View.INVISIBLE);

      } else {

        bean = null;
        // 设置名称
        for (int i = 0; i < typeList.size(); i++) {
          bean = typeList.get(i);
          if (id.equals(bean.getTypeId())) {
            tvTitle.setText(bean.getName());
            break;
          }
        }
        // 设置子分类
        LayoutInflater inflater = LayoutInflater.from(context);
        View layout = inflater.inflate(R.layout.pop_children, null);
        GridView childGridView = (GridView) layout.findViewById(R.id.gv_children);

        final Map<String, String> childMap = bean.getChildType();

        if (childMap != null && childMap.size() > 1) {

          tvChildTitle.setVisibility(View.VISIBLE);
          btnSelectChild.setVisibility(View.VISIBLE);

          final ArrayList<String> list = new ArrayList<String>();

          list.addAll(childMap.keySet());
          list.remove("全部");
          list.add(0, "全部");
          childGridView.setAdapter(new ChildListAdapter(context, list, handler));

          popChildren =
              new PopupWindow(layout, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
          popChildren.setOutsideTouchable(true);


        } else {
          tvChildTitle.setVisibility(View.INVISIBLE);
          btnSelectChild.setVisibility(View.INVISIBLE);
        }

      }
    }


  }

@Override
public void mainTypeChange(String url) {
	initTypeData(url);
}



}
